package com.zw.se2.general;

import com.sun.jersey.api.representation.Form;
import com.zw.se2.generalUtils.RestUtil;
import com.zw.se2.generalUtils.globalVAR;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;

/**
 * Created by Administrator on 2016/7/4.
 */
public class DataExpressProxy {
    private MqttPublish server;
    private static RestUtil restClient;
    private static DataExpressProxy uniqueInstance;
    private static String DataExpressIP;
    private static String dataExpressRestPort;

    public static HashMap<String, Long> getTopicsMap() {
        return topicsMap;
    }

    public static void setTopicsMap(HashMap<String, Long> topicsMapIn) {
        topicsMap = topicsMapIn;
    }

    private static HashMap<String,Long> topicsMap;

    String host;

    private DataExpressProxy() {
        globalVAR GV = new globalVAR();
        GV.initialize();
        topicsMap=new HashMap<String, Long>();
//        CleanerScheduler cleanerScheduler=new CleanerScheduler();
//        cleanerScheduler.main_quartz();
        DataExpressIP = globalVAR.dataExpressIP;
        dataExpressRestPort = globalVAR.dataExpressRestPort;
        restClient = new RestUtil();
        try {
            host = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        try {
            server = new MqttPublish(DataExpressIP, host+System.currentTimeMillis());
        } catch (MqttException e) {
            e.printStackTrace();
        }

    }

    public void subscribe(final DataExpressCallback callback, String topic) {
        try {
            host = "mqttClient" +InetAddress.getLocalHost().getHostName()+ System.currentTimeMillis();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        MqttSubscribe client = new MqttSubscribe(DataExpressIP, host, new MqttCallback() {
            public void connectionLost(Throwable throwable) {

            }

            public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                callback.onMessage(mqttMessage);
            }

            public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

            }
        });
        client.start();
        try {
            client.subscribe(topic);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public static DataExpressProxy getInstance() {

        if (uniqueInstance == null) {
            uniqueInstance = new DataExpressProxy();
        }
        return uniqueInstance;
    }


    public boolean sendMessage(String _context, String _topic) {
        addTopicBeforeSendMessage(_topic);
        if (sendMessageWithoutSave(_context, _topic)) return false;
        return true;

    }

    private boolean sendMessageWithoutSave(String _context, String _topic) {

        try {

            System.out.println("sending MQTT MESSAGE" + " the content is>>>>>>" + _context + ",the topic is <<<<<" + _topic);
            server.publish(_topic, _context);
        } catch (MqttException e) {
            e.printStackTrace();
            return true;
        }
        return false;
    }


    //增加需要存储的主题
    public String addMQTTTopic(String topic) {
//      mqtt模式
        deleteMQTTTopic(topic);
        sendMessageWithoutSave(topic, "needsave");
        return "success";
    }

    //删除需要存储的主题
    public static String deleteMQTTTopic(String topic) {
        //通过REST从DataExpre
        // ss获取数据
        Form form = new Form();
        form.add("topic", topic);
        String url = "http://" + DataExpressIP + ":" + dataExpressRestPort + "/dataexpress/api/v1/needsave";
        String result = restClient.sendRest(url, form, "delete");
        return result;

    }

    //查询需要存储的主题
    public String getMQTTTopics() {
        //通过REST从DataExpre
        // ss获取数据
        Form form = new Form();
        String url = "http://" + DataExpressIP + ":" + dataExpressRestPort + "/dataexpress/api/v1/needsave";
        String result = restClient.sendRest(url, form, "get");
        return result;

    }

    //修改需要存储的主题
    public String updateMQTTTopic(String orginTopic, String targetTopic) {
        String url = "http://" + DataExpressIP + ":" + dataExpressRestPort + "/dataexpress/api/v1/needsave";//"http://localhost:8080/user/testPatch";
        Form form = new Form();
        JSONObject origin = new JSONObject();
        origin.put("topic", orginTopic);
        JSONObject target = new JSONObject();
        target.put("topic", targetTopic);
        form.add("f", origin.toString());
        form.add("u", target.toString());
        String result = restClient.sendRest(url, form, "patch");
        return result;

    }

    //查询指定主题的数据
    public String getSelectedTopicData(String topic) {
        //通过REST从DataExpre
        // ss获取数据
        Form form = new Form();
        form.add("Topic", topic);
        String url = "http://" + DataExpressIP + ":" + dataExpressRestPort + "/dataexpress/api/v1/messages";
        String result = restClient.sendRest(url, form, "get");
        return result;

    }
    public String getDataFromDataExpressWithId(String startTime, String endTime, String topic, int currentPage, int pageSize) {
        int lastNum = topic.lastIndexOf("_");
        String topicWithoutId = topic.substring(0, lastNum );
        String id=topic.substring(lastNum+1);
        String resultWithoutId = getDataFromDataExpress(startTime, endTime, topicWithoutId, currentPage, pageSize);
        JSONObject obj = JSONObject.fromObject(resultWithoutId);
        JSONArray newResult=new JSONArray();
        if (obj.has("result"))
        {
            JSONArray resultArray= obj.getJSONArray("result");
            for(int i=0;i<resultArray.size();i++)
            {
                JSONObject singleResult=resultArray.getJSONObject(i);
                if(!singleResult.getString("topic").contains("realtime"))
                    continue;
                JSONObject messageObject=singleResult.getJSONObject("message");
                JSONObject dataObject=messageObject.getJSONObject("data");
                if(id.equals(dataObject.getString("id")))
                {
                    newResult.add(singleResult);
                }
            }
        }
        obj.put("result",newResult);
        return obj.toString();

    }
    public String getDataFromDataExpress(String startTime, String endTime, String topic, int currentPage, int pageSize) {
        //通过REST从DataExpre
        // ss获取数据
        JSONArray array = new JSONArray();
        Form form = new Form();
        form.add("sTime", Long.valueOf(startTime));
        form.add("eTime", Long.valueOf(endTime));
        form.add("topic", topic);
        form.add("currentPage", currentPage);
        form.add("pageSize", pageSize);
        System.out.println(form.toString());
        String url = "http://" + DataExpressIP + ":" + dataExpressRestPort + "/dataexpress/api/v1/messages";
        String result = restClient.sendRest(url, form, "get");
        return result;

    }
    public String getDataFromDataExpressWithoutTopic(String startTime, String endTime, int currentPage, int pageSize) {
        JSONArray array = new JSONArray();
        Form form = new Form();
        form.add("sTime", Long.valueOf(startTime));
        form.add("eTime", Long.valueOf(endTime));
        form.add("currentPage", currentPage);
        form.add("pageSize", pageSize);
        System.out.println(form.toString());
        String url = "http://" + DataExpressIP + ":" + dataExpressRestPort + "/dataexpress/api/v1/messages";
        String result = restClient.sendRest(url, form, "get");
        return result;

    }
    public void deleteMessagesByTopic(String topic){
        Form form = new Form();
        form.add("topic", topic);
        System.out.println(form.toString());
        String url = "http://" + DataExpressIP + ":" + dataExpressRestPort + "/dataexpress/api/v1/messages";
        restClient.sendRest(url, form, "delete");
    }

    public boolean hasSavedTopic(String topic) {
        String savedTopicJson = getMQTTTopics();
        if (savedTopicJson.contains(topic))
            return true;
        else
            return false;
    }
    public void addTopicBeforeSendMessage(String topic){

        if(!topicsMap.containsKey(topic))
        {
            addMQTTTopic(topic);
        }
        topicsMap.put(topic,System.currentTimeMillis());

    }

}
